package cyou.breathe.yuque;

import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.net.http.HttpClient;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author: breathe
 * @createTime: 2025-07-08
 */
public class TocProcessor {
    private final Path outputDir;
    private final String bookId;
    private final String cookie;
    private final StringBuilder summary = new StringBuilder();

    public TocProcessor(Path outputDir, String bookId, String cookie) {
        this.outputDir = outputDir;
        this.bookId = bookId;
        this.cookie = cookie;
    }

    public void processToc(JsonNode toc) {
        Map<String, String> uuidToPath = new HashMap<>();

        for (JsonNode doc : toc) {
            String type = doc.path("type").asText();
            String uuid = doc.path("uuid").asText();
            String parentUuid = doc.path("parent_uuid").asText();
            String title = doc.path("title").asText().replaceAll("[\\\\/:*?\"<>|]", "_");
            String url = doc.path("url").asText();

            Path parentPath = parentUuid.isEmpty() ? outputDir : outputDir.resolve(uuidToPath.getOrDefault(parentUuid, ""));
            String parentFileName = parentPath.getFileName().toString();
            System.out.println(parentFileName);
            if (parentFileName.endsWith(".md")) {
                String dirName = parentFileName.substring(0, parentFileName.length() - 3);
                parentPath = parentPath.getParent().resolve(dirName);
            }
            Path thisPath = parentPath.resolve(title + (url.isEmpty() ? "" : ".md"));
            System.out.println("Path: " + thisPath);
            try {
                if (!Files.exists(thisPath.getParent())) {
                    Files.createDirectories(thisPath.getParent());
                }
                if (url.isEmpty()) {
                    // 目录节点
                    uuidToPath.put(uuid, outputDir.relativize(thisPath).toString());
                    summary.append("## ").append(title).append("\n");
                } else {
                    // 文档节点
                    uuidToPath.put(uuid, outputDir.relativize(thisPath).toString());
                    summary.append("* [").append(title).append("](")
                            .append(outputDir.relativize(thisPath)).append(")\n");

                    // 调用 Markdown 下载器保存页面
                    MarkdownDownloader.savePage(bookId, url, thisPath, cookie);
                    Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 3000));
                }
            } catch (IOException | InterruptedException e) {
                System.err.println("处理 TOC 节点失败: " + e.getMessage());
            }
        }
    }

    public String getSummaryMarkdown() {
        return summary.toString();
    }
}

